package com.zorn.core.spring.mvc.support;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zorn.core.util.ParameterParser;

public class ControllerSupport extends AbstractController {

	@Autowired
	private HttpServletRequest request;

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpSession getSession() {
		return getRequest().getSession();
	}

	public HttpSession getSession(boolean create) {
		return getRequest().getSession(create);
	}

	public String getRealPath(String path) {
		return getServletContext().getRealPath(path);
	}

	public String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	public String getParameter(String name, String def) {
		String param = getRequest().getParameter(name);

		if (param == null) return def;

		return param;
	}

	public String[] getParameterValues(String name) {
		return getRequest().getParameterValues(name);
	}

	public Map<String, Object> getParameterMap() {
		return getParameterMap(true);
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> getParameterMap(boolean parse) {
		return ParameterParser.parse(getRequest().getParameterMap());
	}

	public JSONObject getParameterJSONObject() {
		return new JSONObject(getParameterMap(true));
	}

	public JSONObject getParameterJSONObject(boolean parse) {
		return new JSONObject(getParameterMap(parse));
	}

	@SuppressWarnings("unchecked")
	public Object getBean(Class cls) {
		return ContextLoader.getCurrentWebApplicationContext().getBean(cls);
	}

	public Object getBean(String cls) {
		return ContextLoader.getCurrentWebApplicationContext().getBean(cls);
	}

	protected String toJSONString(Object result) {
		return JSON.toJSONString(result);
	}

	protected String toJSONString(Object result, boolean dateformat) {
		if (dateformat) {
			return toJSONString(result, JSON.DEFFAULT_DATE_FORMAT);
		} else {
			return JSON.toJSONString(result);
		}
	}

	protected String toJSONString(Object result, String dateformat) {
		return JSON.toJSONStringWithDateFormat(result, dateformat);
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return null;
	}
}
